package com.yangfan.thread.interview_questions;

/**
 * @description: 面试题2
 * @author: yangfan
 * @date: Created in 2020/2/13 0013 15:42
 * @modified By:
 */
public class ThreadConcurrencyIssue2 {

    //https://www.jianshu.com/p/931e2ea582ee
    //题目二：写两个线程，一个线程打印1-52，另一个线程打印A-Z，打印顺序是12A34B...5152Z；

    public enum CONTROL {
        ZERO,ONE;
    }

    //判断类型
    private static CONTROL control = CONTROL.ZERO;

    //锁
    private static final Object LOCK = new Object();


    public static void main(String[] args) {

        ThreadConcurrencyIssue2 t = new ThreadConcurrencyIssue2();

        //打印1-52
        new Thread(){
            @Override
            public void run() {
                try {
                    for (int i = 0; i < 26; i++) {
                        t.printNum();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();


        //打印A到Z
        new Thread(){
            @Override
            public void run() {
                try {
                    for (int i = 0; i < 26; i++) {
                        t.printChar();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

    int count = 1;

    void printNum() throws InterruptedException {

        synchronized (LOCK){

            while (control == CONTROL.ONE)
                LOCK.wait();

            System.out.print(((count) *2)-1);
            System.out.print((count) *2);

            count++;

            //打印完成

            control = CONTROL.ONE;//把控制权 交给 打印字母
            LOCK.notifyAll();

        }

    }

    char letter = 'A' ;

    void printChar() throws InterruptedException {

        synchronized (LOCK){

            while (control == CONTROL.ZERO)
                LOCK.wait();

            System.out.print(letter++);

            //打印完成

            control = CONTROL.ZERO;//把控制权 交给 打印数字
            LOCK.notifyAll();

        }

    }

}
